import { app, BrowserWindow, ipcMain, powerMonitor, screen, globalShortcut } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import { setupProtocolListener } from './utils/protocol'
import { checkInternal } from './utils/index'
import store from './store/index'
import { initAegis, reportEvent, info, error, report, reportTime, setUser } from './utils/aegis'
import shortcutManager from './utils/shortcutManager'
import log from 'electron-log'
import { createProxyServer } from './utils/requestProxy'

// 创建窗口实例化
import AiIconWindow from './windows/AiIconWindow'
import AiChatWindow from './windows/AiChatWindow'
import ScreenRecorderWindow from './windows/ScreenRecorderWindow'
import DiscussionGroupWindow from './windows/discussionGroupWindow'
import MoreFeaturesWindow from './windows/MoreFeaturesWindow'
import RightClickMenuWindow from './windows/RightClickMenuWindow'
import BrowserViewWindow from './windows/BrowserViewWindow'
import UserManagementWindow from './windows/UserManagementWindow'

// 渲染进程向主进程通信的实例化
import eventRouter from './router/EventRouter'
// 路由
import routers from './router/routers'

// 获取单例锁
const gotTheLock = app.requestSingleInstanceLock()




if (!gotTheLock) {
  app.quit()
} else {
  log.info('应用启动')
  log.info('用户信息', store.get('userInfo'))
  // 尽早初始化 Aegis
  initAegis()
  setupProtocolListener() // 设置协议监听

  // 代码片段所在：app.whenReady().then(async () => { ... }) 回调内
  app.whenReady().then( async() => {
    // 为windows设置应用程序用户模型id
    electronApp.setAppUserModelId('assistant.ai.lightbox')
    
    // 在开发中默认使用F12打开或关闭DevTools
    app.on('browser-window-created', (_, window) => { optimizer.watchWindowShortcuts(window) })

    // 创建代理服务器（使用 await 并捕获错误，便于定位失败原因）
    try {
      const proxyPort = await createProxyServer()
      log.info('代理服务端口:', proxyPort)
    } catch (e) {
      log.error('代理服务启动失败:', e)
    }

    // 检查是否在内部网络
    checkInternal('yst.woa.com').then(res => {
      store.set('isIntranet', res || false)
    })

    // 检查快捷键是否被占用
    const prev = store.get('applicationSettings')
    const shortcuts = shortcutManager.getInstance()
    const keys = [
      'evokeChortcut',
      'screenshotChortcut',
      'screenRecordingChortcut',
      'chatChortcut'
    ]
    if (prev && prev.shortcuts) {
      for (const key in prev.shortcuts) {
        const accelerator = prev.shortcuts[key]
        if (typeof accelerator === 'string' && accelerator.trim() && keys.includes(key)) {
          prev.shortcuts['is' + key] = globalShortcut.register(accelerator, () => {})
          shortcuts.unregister(accelerator)
        }
      }
      store.set('applicationSettings', { ...prev })
    }

    // 窗口实例化
    const aiIconWindow = new AiIconWindow()
    const aiChatWindow = new AiChatWindow()
    const screenRecorderWindow = new ScreenRecorderWindow()
    const discussionGroupWindow = new DiscussionGroupWindow()
    const moreFeaturesWindow = new MoreFeaturesWindow()
    const rightClickMenuWindow = new RightClickMenuWindow()
    const browserViewWindow = new BrowserViewWindow()
    const userManagementWindow = new UserManagementWindow()

    // 创建窗口
    aiIconWindow.create()
    aiChatWindow.create()
    discussionGroupWindow.create()
    moreFeaturesWindow.create()
    rightClickMenuWindow.create()
    browserViewWindow.create()
    userManagementWindow.create()

    // 添加所有窗口共享的 eventRouter
    eventRouter.addApi('aiIconWindow', aiIconWindow)
    eventRouter.addApi('aiChatWindow', aiChatWindow)
    eventRouter.addApi('screenRecorderWindow', screenRecorderWindow)
    eventRouter.addApi('discussionGroupWindow', discussionGroupWindow)
    eventRouter.addApi('moreFeaturesWindow', moreFeaturesWindow)
    eventRouter.addApi('rightClickMenuWindow', rightClickMenuWindow)
    eventRouter.addApi('browserViewWindow', browserViewWindow)
    eventRouter.addApi('userManagementWindow', userManagementWindow)
    eventRouter.addApi('app', app)

    // 添加所有事件
    eventRouter.addRouters(routers)

    //渲染进程 向 主进程通信
    ipcMain.handle('renderer-to-main', (_e, data) => {
      return eventRouter.router(data)
    })

    // 获取鼠标位置
    ipcMain.handle('get-cursor-screen-point', (_e) => {
      return screen.getCursorScreenPoint()
    })

    // Aegis IPC 处理器
    ipcMain.handle('aegis-call', (_e, { method, args }) => {
      try {
        switch (method) {
          case 'reportEvent':
            return reportEvent(args[0], args[1]);
          case 'info':
            return info(args[0], args[1]);
          case 'error':
            return error(args[0], args[1]);
          case 'report':
            return report(args[0], args[1]);
          case 'reportTime':
            return reportTime(args[0], args[1]);
          case 'setUser':
            return setUser(args[0]);
          default:
            console.warn('未知的 Aegis 方法:', method);
        }
      } catch (err) {
        console.error('Aegis IPC 调用失败:', err);
      }
    })

    // 获取代理端口
    ipcMain.handle('get-proxy-port', () => {
      const proxyPort = store.get('proxyPort')
      return proxyPort
    })

    // 每隔10分钟检查一次是否在 intranet
    setInterval(() => {
      checkInternal('yst.woa.com').then(res => {
        store.set('isIntranet', res || false)
      })
    }, 1000 * 60 * 10)

    // 监听电源变化事件
    powerMonitor.on('resume', () => {
      setTimeout(() => {
        aiIconWindow.create()
        aiChatWindow.create()
      }, 100)
    });

    // macOS 下，当用户点击 Dock 图标重新激活应用时，如果没有任何窗口打开，就重新创建主窗口。
    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) aiIconWindow.create()
    })

    // 监听屏幕分辨率变化事件
    screen.on('display-metrics-changed', (_event, _display, _changedMetrics) => {
      const pos = aiIconWindow.getPosition()
      aiIconWindow.refreshPosition(pos[0], pos[1])
    });

  }).catch(err => {
    console.error('App init failed:', err);
  });

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })
  app.on('will-quit', () => {
    // 注销所有快捷键
    shortcutManager.getInstance().unregisterAll()
  })
}
